package one.stand.config;

import lombok.extern.slf4j.Slf4j;
import one.stand.model.CompanyCouponModel;
import one.stand.model.UserCouponModel;
import one.stand.model.essay.TaskCustomerModel;
import one.stand.model.essay.TaskStaffModel;
import one.stand.service.BaseService;
import one.stand.util.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 任务定时器 1分钟检查一次任务状态 如果已经过期的任务自动结束 ，未开始的任务自动开始
 * @author luoyang
 * @date 2020/5/28 11:11
 */
@Service
@Slf4j
public class TaskCutomerService extends BaseService {
    @Scheduled(cron = "0 */1 * * * ?")
    public void build() {
        log.info("开始任务检查:..", LocalDateTime.now());
        //1 任务检查未开始
        List<TaskCustomerModel> models = this.taskCustomerMapper.queryTaskAll(1, DateUtil.now());
        if(!CollectionUtils.isEmpty(models)){
            models.forEach(model -> {
                if(model.getStartTime().getTime() < DateUtil.now().getTime()){
                    //任务开始
                    model.setState(0);
                    this.taskCustomerMapper.update(model);
                }
            });
        }
        //0进行中 
        models = this.taskCustomerMapper.queryTaskAll(0, DateUtil.now());
        if(!CollectionUtils.isEmpty(models)){
            models.forEach(model -> {
                if(model.getEndTime().getTime() < DateUtil.now().getTime()){
                    //任务结束
                    model.setState(2);
                    this.taskCustomerMapper.update(model);
                }
            });
        }

        //员工任务检查 过期的任务自动结束
        List<TaskStaffModel> taskStaffModels = this.taskStaffMapper.queryAllTask(DateUtil.now());
        if(!CollectionUtils.isEmpty(taskStaffModels)){
            taskStaffModels.forEach(taskStaffModel -> {
                //根据时间检查任务状态
//                if(taskStaffModel.getStartTime().getTime() < DateUtil.now().getTime()){
//                    taskStaffModel.setState(0);
//                    this.taskStaffMapper.update(taskStaffModel);
//                }
                //任务结束
                if(taskStaffModel.getEndTime().getTime() < DateUtil.now().getTime()){
                    taskStaffModel.setState(2);
                    this.taskStaffMapper.update(taskStaffModel);
                }
            });
        }
        log.info("结束任务检查:..", LocalDateTime.now());
    }

    @Scheduled(cron = "0 */1 * * * ?")
    public void buildCoupon() {
        log.info("开始优惠券检查:..", LocalDateTime.now());

        //查询未使用过期时间小于当前时间的优惠券
        List<UserCouponModel> models = this.userCouponMapper.queryAll();
        models.forEach(model ->{
            model.setCouponState(3);
            this.userCouponMapper.updateByPrimaryKeySelective(model);
        });

        log.info("结束优惠券检查:..", LocalDateTime.now());
    }
}
